//
//  FileUtil.m
//  SWIOSLibary
//
//  Created by shaowei on 13-7-21.
//  Copyright (c) 2013年 LianZhan. All rights reserved.
//

#import "SWFileUtil.h"

@implementation SWFileUtil

+ (unsigned long long)fileOrDirSizeAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    if (![fileManager fileExistsAtPath:filePath isDirectory:&isDir]) {
        SWASSERT(0,@"路径：%@ 不存在",filePath);
        return 0;
    }
    
    if (isDir) {
        //目录
        NSArray *itemArray = [fileManager subpathsAtPath:filePath];
        unsigned long long finalSize = 0;
        for (NSString *item in itemArray) {
            NSString *itemPath = [filePath stringByAppendingPathComponent:item];
            finalSize += [[fileManager attributesOfItemAtPath:itemPath error:nil] fileSize];
        }
        
        return finalSize;
    }else{
        //文件
        return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
}

/**
 *	获取指定路径文件（或目录）的大小
 *
 *	@param	folderPath	指定文件（或目录）路径
 *
 *	@return	文件（或目录）的详细大小(key:size)和单位(key:unit)，自动匹配显示合适的计量单位
 */
+ (NSDictionary *)fileOrDirSizeDetailAtPath:(NSString *)filePath{
    unsigned long long originSize = [SWFileUtil fileOrDirSizeAtPath:filePath];
    
    int caculateNum = 0;
    while ((originSize / pow(1024, caculateNum)) > 1024) {
        caculateNum++;
    }
    
    CGFloat resultSize = caculateNum?(originSize / pow(1024, caculateNum)):originSize;
    NSString *sizeString = SWString(@"%.2f",resultSize);
    
    NSString *unit = nil;
    switch (caculateNum) {
        case 0: { unit = @"B"; }break;
        case 1: { unit = @"KB"; }break;
        case 2: { unit = @"MB"; }break;
        case 3: { unit = @"GB"; }break;
        case 4: { unit = @"TB"; }break;
            
        default:
            SWASSERT_SWITCH_OVER;
            break;
    }
    
    return @{@"size":sizeString,@"unit":unit};
}

+ (BOOL)removeDirCacheContent:(NSString *)dirPath exceptForKey:(NSString *)nameKey{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileArray = [fileManager subpathsOfDirectoryAtPath:dirPath error:nil];
    
    BOOL result = (fileArray != nil);
    
    for (NSString *fileName in fileArray) {
        if ([fileName rangeOfString:nameKey].length != 0) {
            continue;
        }
        NSString *filePath = [dirPath stringByAppendingPathComponent:fileName];
        BOOL isDir = NO;
        if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && (!isDir)) {
            //文件
            result = result && [fileManager removeItemAtPath:filePath error:nil];
            
        }
        
    }
    
    return result;
}


@end
